#!/usr/bin/python2.4
#
#Copyright 2009 Google Inc.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#

"""Image handler module.

This module provides request handler for fetching images from AppEngine db.
"""

import logging
import constants
import db_utils
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class ImageHandler(webapp.RequestHandler):
  """Request Handler to handle image fetch requests.

  This class resolves all /static/images/*.* requests. Given image name, it
  uses GetImage API of DbHandler to fetch image blob and write of response
  stream with content type as image/text_of_image.
  """

  def get(self):
    """GET method for this request handler."""
    db_handler = db_utils.DbHandler()
    url = self.request.uri
    index = url.find(constants.IMAGE_PATH + '/')
    image_url = url[index:]
    parts = image_url.split('/')
    image_name = parts[len(parts) - 1]
    (name, extension) = image_name.split('.')
    logging.debug('image name:' + name)
    image_data = db_handler.GetImage(image_url)
    self.response.headers['Content-Type'] = 'image/' + extension
    self.response.out.write(image_data)


application = webapp.WSGIApplication([(constants.IMAGE_PATH + '/.*', ImageHandler)],
                                     debug=True)


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
